package com.dingli.servlet;

import com.dingli.DAO.AdminDao;
import com.dingli.entity.Person;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "ChangeInfoServlet", value = "/updateUserInfo")
public class UpdateUserInfoServlet extends HttpServlet {
    private AdminDao adminDao = new AdminDao();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String old = request.getParameter("oldPassword");
        String password = request.getParameter("newpassword");
        String confirm = request.getParameter("confirmPassword");
        HttpSession session = request.getSession();
        int id = ((Person)session.getAttribute("user")).getId();
        try {
            if(adminDao.confirmUser(id, old) || !password.equals(confirm)){
                response.sendRedirect("/views/error.jsp");
            }
            else{
                int flag = adminDao.updateInfo(id, email, password);
                if(flag > 0){
                    response.sendRedirect("/logout");
                }
            }
        }
        catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
